from apps.libs.error_code import Success, DeleteSuccess, AuthFailed
from apps.libs.redprint import Redprint
from apps.libs.token_auth import auth
from apps.models.base import db
from apps.models.user import User
from flask import jsonify, g

api = Redprint('user')

@api.route('/<int:uid>', methods=['POST'])
@auth.login_required
def get_user(uid):
    user = User.query.get_or_404(uid)
    return jsonify(user)


@api.route('/delete', methods=['DELETE'])
@auth.login_required
def delete_user():
    # 防止用户超权操作
    uid = g.user.uid
    with db.auto_commit():
        user = User.query.filter_by(id=uid, status=1).first_or_404()
        user.delete()
    return DeleteSuccess()


@api.route('/<int:uid>', methods=['GET'])
@auth.login_required
def super_get_user(uid):
    is_admin = g.user.is_admin
    if not is_admin:
        raise AuthFailed()
    user = User.query.filter_by(id=uid).first_or_404()
    return jsonify(user)

@api.route('/<int:uid>', methods=['DELETE'])
@auth.login_required
def super_delete_user(uid):
    with db.auto_commit():
        user = User.query.filter_by(id=uid).first_or_404()
        user.delete()
    return DeleteSuccess()
